package leetcode.mapCode.week1.K99;

import java.util.Arrays;
import java.util.Scanner;

/**
 * description :
 * author Ahang :
 * create : 2025-11-04 14:05
 */
public class Main {
    static boolean[][] visited;
    static int[][] DIR = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public static void main(String[] args) {
//        数据输入
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int[][] graph = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int x = scanner.nextInt();
                graph[i][j] = x;
            }
        }
        visited = new boolean[n][m];
        for (boolean[] row : visited) {
            Arrays.fill(row, false);
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (graph[i][j] == 1 && visited[i][j] == false) {
                    visited[i][j] = true;
                    ans++;
                    dfs(graph, i, j);
                }
            }
        }
        System.out.println(ans);
    }

    static void dfs(int[][] graph, int x, int y) {
        for (int i = 0; i < 4; i++) {
            int newX = x + DIR[i][0];
            int newY = y + DIR[i][1];
            if (newX<0||newX>=graph.length){
                continue;
            }
            if (newY<0||newY>=graph[0].length){
                continue;
            }
            if (graph[newX][newY]==1&&visited[newX][newY]==false){
                visited[newX][newY] = true;
                dfs(graph,newX,newY);
            }
        }
    }
}
